package com.toidep.activities;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.toidep.R;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseActivity;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.interfaces.ResponseListener;
import com.toidep.payment.PaymentControl;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.DialogUtility;

public class LoginActivity extends BaseActivity {

	private EditText username, password;
	private Button button_login, button_register;
	private boolean invalidToken;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		ConfigUtility.getConfig(LoginActivity.this);
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_login);
		
		if (ConfigUtility.os_version > 10) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		
		button_login = (Button) findViewById(R.id.button_login);
		button_register = (Button) findViewById(R.id.button_register);
		
		button_login.setOnClickListener(onClickLogin);
		button_register.setOnClickListener(onClickRegister);
		
		invalidToken = getIntent().getBooleanExtra("invalid_token", false);
	}
	
	private OnClickListener onClickLogin = new OnClickListener() {
		@Override
		public void onClick(View v) {
			final String str_username = username.getText().toString();
			final String str_password = password.getText().toString();
			
			if (isValid(str_username) && (isValid(str_password))) { // Hop le, xu ly login
				doLogin(str_username, str_password);
			} else { // Username hoac Password khong hop le
				DialogUtility.showDialogAlert(LoginActivity.this, "", getString(R.string.text_invalid_login),
						getString(R.string.label_close), null);
			}
		}
	};
	
	private OnClickListener onClickRegister = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
			
			startActivityForResult(intent, Constants.REQUEST_CODE_REGISTER);
			
		}
	};
	
	private void setResultForFinish() {
		if (invalidToken) {
			startActivity(new Intent(this, MainActivity.class));
		} else {
			
			SharePreference sharePreference = SharePreference.getInstance(this);
			Intent intent = new Intent();
			if (sharePreference.getLoginStatus() == true)
				setResult(1, intent);
			else
				setResult(0, intent);
		}
		finish();
	}

	private void doLogin(final String username,final String password) {
		ApiController.login(LoginActivity.this, username, password,
			new ResponseListener() {
				
				@Override
				public void processResponse(int inintstall) {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void processResponse(final String response) {
					//Bug #288, #227 - start
					Log.e("Login Response", response);
					
					if (response != null) {
						JSONObject jsonObject = null;
						try {
							jsonObject = new JSONObject(response);
							int code = ParseJSON.getIntValue(jsonObject, Constants.PARAM_REQUEST_CODE);
							if(code==1){
								JSONObject data = new JSONObject(ParseJSON.getStringValue(jsonObject , Constants.PARAM_RESPONSE_DATA));
//								String token = ParseJSON.getStringValue(data , Constants.PARAM_RESPONSE_TOKEN);
								String token = data.getString(Constants.PARAM_RESPONSE_TOKEN);
								SharePreference ioeShare = SharePreference.getInstance(LoginActivity.this);
								ioeShare.putAccessToken(token);
								
								String message = ParseJSON.getStringValue(jsonObject, "message");
								if(message!=null){
									if(message.equalsIgnoreCase("Nạp tiền để hoàn thành đăng ký")){
										System.out.println("Nạp tiền để hoàn thành đăng ký");
										PaymentControl paymentControl = new PaymentControl(LoginActivity.this);
										paymentControl.setListener(new ResponseListener() {
											
											@Override
											public void processResponse(int inintstall) {
												if(inintstall==1){
													SharePreference ioeShare = SharePreference.getInstance(LoginActivity.this);
													ioeShare.putUserName(username);
													ioeShare.putPassword(password);
													ParseJSON.getUserInfoFromResponse(LoginActivity.this, response);
													
													setResultForFinish();
												}
											}
											
											@Override
											public void processResponse(String response) {
												
											}
										});
										paymentControl.showDialogPaymentStart();
									}else{
										SharePreference ioeShare1 = SharePreference.getInstance(LoginActivity.this);
										ioeShare1.putUserName(username);
										ioeShare1.putPassword(password);
										
										ParseJSON.getUserInfoFromResponse(LoginActivity.this, response);
										
										setResultForFinish();
									}
								}
								
							}else{
								DialogUtility.showDialogAlert(LoginActivity.this, "",
										"Tên tài khoản hoặc mật khẩu không đúng, yêu cầu nhập lại",
										LoginActivity.this.getString(R.string.label_close), null);
							}
							
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					//Bug #288, #227 - end
				}
			});
	}
	
	/*
	 * Kiem tra du lieu dau vao
	 */
	private boolean isValid(String text) {
		boolean valid = false;
		if (text != null) {
			text = text.trim();
			if (text.length() > 0) {
				valid = true;
			}
		}
		return valid;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode > 0) {
			switch (requestCode) {
			case Constants.REQUEST_CODE_REGISTER:
				setResultForFinish();
				break;
			}
		}else if(requestCode ==Constants.REQUEST_CODE_REGISTER ){
			if(resultCode ==0 ){
			finish();
			}
		}
	
		super.onActivityResult(requestCode, resultCode, data);
	}
}
